package my.leetcode.solution.jianzhi_offer;

public class P24 {

    public static void main(String[] args) {
        ListNode a = new ListNode(1);
        a.next = new ListNode(2);
        a.next.next = new ListNode(3);
        a.next.next.next = new ListNode(4);
        a.next.next.next.next = new ListNode(5);
        ListNode b = reverseList(a);
        while(b != null) {
            System.out.println(b.val);
            b=b.next;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public static ListNode reverseList(ListNode head) {
        ListNode pre = head, now = head.next, next;
        if(now == null) {
            return head;
        }
        head.next = null;
        next = now.next;
        do {
            now.next = pre;
            pre = now;
            now = next;
        } while((next = now.next) != null);
        now.next = pre;
        return now;
    }

}
